package com.etone.system.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.etone.common.utils.DateUtils;
import com.etone.common.utils.http.HttpUtils;
import com.etone.system.domain.*;
import com.etone.system.mapper.*;
import com.etone.system.service.ITurnoverInventoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class TurnoverInventoryServiceImpl implements ITurnoverInventoryService {

    @Autowired
    private ITurnoverInventoryMapper iTurnoverInventoryMapper;

    @Autowired
    private FiveTaskinfoMapper fiveTaskinfoMapper;

    @Autowired
    private SysDibiaoMapper dibiaoMapper;

    @Autowired
    private AgvMapper agvMapper;

    @Autowired
    private SysStorageMapper sysStorageMapper;

    @Autowired
    private FiveCtuRecordMapper fiveCtuRecordMapper;

    @Autowired
    private SixWuliaoinfoMapper sixWuliaoinfoMapper;

    @Autowired
    private SixFreetaskMapper sixFreetaskMapper;

    @Override
    public int addTurnoverInventory(List<TurnoverInventory> list) {
        String huojiano = null;
        //物料溯源表
        //校验物料编号是否在溯源表中存在，如果存在则删除
        for(TurnoverInventory turnoverInventory : list){
            huojiano = turnoverInventory.getCangweiNo().substring(0,6);
            sixWuliaoinfoMapper.deleteSixWuliaoinfoBywuliaocode(turnoverInventory.getWuliaoNo());
        }
        boxBack(huojiano);
        //  保存物料与仓位绑定关系
        int i = iTurnoverInventoryMapper.addTurnoverInventory(list);
        //  根据仓位更改存储状态
        int j = iTurnoverInventoryMapper.updateSysStorage(list);

        int g = sixWuliaoinfoMapper.insertSixWuliaoinfoList(list);
        // TODO : 调用agv小车没写
        AgvServiceImpl.callAgv(list, "0", fiveTaskinfoMapper, dibiaoMapper, agvMapper, sysStorageMapper,
                fiveCtuRecordMapper,sixWuliaoinfoMapper,iTurnoverInventoryMapper,sixFreetaskMapper);
        return i;
    }

    @Override
    public int badBack(List<TurnoverInventory> list) {
        //  保存物料与仓位绑定关系
        int i = 0;
//        iTurnoverInventoryMapper.addTurnoverInventory(list);
//        //  根据仓位更改存储状态
//        int j = iTurnoverInventoryMapper.updateSysStorage(list);
//        // TODO : 调用agv小车没写
//        AgvServiceImpl.callAgv(list, "3", fiveTaskinfoMapper, dibiaoMapper, agvMapper, sysStorageMapper, fiveCtuRecordMapper);
        return i;
    }

    @Override
    public Map<String, Object> selectTurnoverInventoryList(int page, int pageSize, String wuliaoNo, int status) {
        Map<String, Object> map = new HashMap<>();
        //开启分页，下面紧跟查询语句(查询全部数据)
        PageHelper.startPage(page, pageSize);
        List<Map<String, Object>> list = iTurnoverInventoryMapper.selectTurnoverInventoryList(wuliaoNo, status);        //进行分页
        PageInfo pageInfo = new PageInfo(list);
        List infoList = pageInfo.getList();
        long total = pageInfo.getTotal();
        map.put("total", total);
        map.put("data", infoList);
        return map;
    }

    @Override
    public List<Map<String, Object>> selectSysStorageList() {
        //  获取货架信息
        List<Map<String, Object>> paiList = iTurnoverInventoryMapper.selectPaiList();

        paiList.forEach(pai -> {
            Long id = Long.valueOf(pai.get("id").toString());
            //  获取列信息
            List<Map<String, Object>> lieList = iTurnoverInventoryMapper.selectLieList(id);
            pai.put("children", lieList);
            lieList.forEach(lie -> {
                Long id1 = Long.valueOf(lie.get("id").toString());
                //  获取层信息
                List<Map<String, Object>> ceList = iTurnoverInventoryMapper.selectCeList(id1);
                lie.put("children", ceList);
            });
        });
        return paiList;
    }

    @Override
    public Map<String, Object> addTurnoverOutbound(List<TurnoverInventory> list) {
        //地标上有货架、并且是空的并且没有正在进行的出库任务
        Map<String, Object> data = new HashMap<>();
        //  判断出库周转区是否有货位sys_arrange
        SysDibiao sysDibiao =  new SysDibiao();
        sysDibiao.setType(3l);
        List<SysDibiao> dblists = dibiaoMapper.selectSysNotFreeDibiaoList1(sysDibiao);
//        List<Map<String, Object>> mapList = iTurnoverInventoryMapper.selectArrange();
//        if (dblists.size() == 0) {
//            data.put("code", 100);
//            data.put("msg", "出库周转区无货架！");
//        } else {
        if(dblists.size()!=0){
            String type = String.valueOf(dblists.get(0).getHuojia());
            // 判断出库周转货架是否为空货架
//            int j = iTurnoverInventoryMapper.countIsRequest(type);
//            if (j > 0) { // 不是空货架
//                data.put("code", 100);
//                data.put("msg", "出库周转区货架不为空，可能上一批出库还没有结束");
//            } else {
            //  空货架  绑定物料编码，调用ctu小车
            // 通过type获取货架仓位号
            //恢复货架上仓位的初始状态
            boxBack(type);
            iTurnoverInventoryMapper.updateStorageStatusByLieType(type);
            List<Map<String, Object>> maps = iTurnoverInventoryMapper.selectStorageByType(type);
            for (int i = 0; i < list.size(); i++) {
                String cangweiNo = String.valueOf(maps.get(i).get("cangweiNo"));
                list.get(i).setCangweiNo(cangweiNo);
            }
            // 记录保存仓位与物料号
            int h = iTurnoverInventoryMapper.addTurnoverInventory(list);
            //  修改仓位状态
            int l = iTurnoverInventoryMapper.updateSysStorage(list);
            // TODO 调用ctu小车
            Map<String, Object> a = AgvServiceImpl.callCCTUAgv(list, fiveCtuRecordMapper, sysStorageMapper, agvMapper, fiveTaskinfoMapper, dibiaoMapper);
            data.put("code", 200);
            data.put("msg", "出库物料与仓位绑定成功！");
            data.put("list", list);
            if(!a.get("code").toString().equals("200")){
                data = new HashMap<>();
                data.putAll(a);
            }
//            }
//        }
        }else{
            data.put("code", 100);
            data.put("msg", "无可用搬运货架！");
        }
//        else{
//            SixFreetask sixFreetask = new SixFreetask();
//            sixFreetask.setType("6");
////            sixFreetask.setTaskModeltype("");
//            Gson gson = new Gson();
//            String json1 = gson.toJson(list);
//            sixFreetask.setWuliaoInfo(json1.toString());
////                sixFreetask.setStartp();
////                sixFreetask.setEndp();
////                sixFreetask.setHuojia();
////                sixFreetask.setStartText();
////                sixFreetask.setEndText();
//            sixFreetaskMapper.insertSixFreetask(sixFreetask);
//            data.put("code", 200);
//            data.put("msg", "出库物料与仓位绑定成功！");
//        }
        return data;
    }

    @Override
    public int urgentTurnoverOutbound(List<TurnoverInventory> list) {
        String huojiano = null;
        //校验物料编号是否在溯源表中存在，如果存在则删除
        for(TurnoverInventory turnoverInventory : list){
            huojiano = turnoverInventory.getCangweiNo().substring(0,6);;
            sixWuliaoinfoMapper.deleteSixWuliaoinfoBywuliaocode(turnoverInventory.getWuliaoNo());
        }
        boxBack(huojiano);
        //  保存物料与仓位绑定关系
        int i = iTurnoverInventoryMapper.addTurnoverInventory(list);
        //  根据仓位更改存储状态
        int j = iTurnoverInventoryMapper.updateSysStorage(list);
        //物料溯源表
        int g = sixWuliaoinfoMapper.insertSixWuliaoinfoList(list);
        // TODO : 调用agv小车直接到出库位   加急潜伏
        AgvServiceImpl.callAgv(list, "2", fiveTaskinfoMapper, dibiaoMapper, agvMapper, sysStorageMapper,
                fiveCtuRecordMapper,sixWuliaoinfoMapper,iTurnoverInventoryMapper,sixFreetaskMapper);
        return i;
    }

    @Override
    public Map<String, Object> boxBack(String cangweiNo) {
        Map<String, Object> map = new HashMap<>();
        // 查询出库周转区是不是为空
//        SysDibiao sysDibiao = iTurnoverInventoryMapper.selectSysDibiao();
//        if(sysDibiao.getHuojia() !=null){
//            if(StringUtils.isEmpty(sysDibiao.getHuojia())){
//                map.put("code",100);
//                map.put("msg","出库周转区暂时有货架，请稍后执行！");
//            }
//        }else {
        String huojiahao = cangweiNo.substring(0, 6);
//        SysDibiao sysDibiao1 = iTurnoverInventoryMapper.selectSysDibiaoByHuojiahao(huojiahao);
        //  判断是否正常移位
//        String endName;
//        if ("0".equals(sysDibiao1.getMark())) { // 正常移位
//            SysDibiao sysDibiao = iTurnoverInventoryMapper.selectSysDibiao();
//                if (sysDibiao!=null) {
//                    if (StringUtils.isEmpty(sysDibiao.getHuojia())) {
//                        map.put("code", 100);
//                        map.put("msg", "出库周转区暂时有货架，请稍后执行！");
//                        return map;
//                    }
//                } else {
//                    endName = "SOS";
//                    //将出库货架所有关联货位状态为free
//                    // bindcangweiornobind(huojiahao, 0, 0);
//                    Map<String, Object> a = AgvServiceImpl.operateFreeHuojia("Q6", 4l, 3l, huojiahao, "出库位---> 出库周转区", "普通背货架agv执行空货架搬运任务---", dibiaoMapper, fiveTaskinfoMapper,sixFreetaskMapper);
//                    if(a.get("code").toString().equals("100")){
//                        return a;
//                    }
//                }
//        } else {  //  加急移位
//            List<SysDibiao> list = iTurnoverInventoryMapper.selectDibiaoList();
//            endName = list.get(0).getName();
//            Map<String, Object> a = AgvServiceImpl.operateFreeHuojia("Q4", 4l, 1l, huojiahao, "加急潜伏---出库位直接到入库位", "普通背货架agv执行空货架搬运任务---", dibiaoMapper, fiveTaskinfoMapper,sixFreetaskMapper);
//            if(a.get("code").toString().equals("100")){
//                return a;
//            }
//        }
        //解绑
//        SixWuliaoinfo sixWuliaoinfo = new SixWuliaoinfo();
//        sixWuliaoinfo.setHuojiaCode(huojiahao);
//        List<SixWuliaoinfo> selectSixWuliaoinfoList =
//                sixWuliaoinfoMapper.selectSixWuliaoinfoList(sixWuliaoinfo);
//        SysDibiao sysDibiao = new SysDibiao();
//        sysDibiao.setHuojia(huojiahao);
//        List<SysDibiao> dibiaos = dibiaoMapper.selectSysDibiaoList(sysDibiao);
//        if(dibiaos.size()!=0){
//            SysDibiao dibiao = dibiaos.get(0);
//            String dibiaoType = dibiao.getType().toString();
//            if(dibiaoType.equals("4")){
                //获取货架对应的所有仓位号
                SysStorage sysStorage = new SysStorage();
                sysStorage.setLieType(huojiahao);
                List<Map<String,Object>> lists = sysStorageMapper.selectSysStorageList(sysStorage);
                if(lists.size()!=0){
                    for(Map<String,Object> map1 : lists){
                        String aa = gainStr(map1.get("cangweiNo").toString());
                        System.out.println("仓位解绑接口返回值======="+aa);
                    }
                    //将货架关联的物料信息清空，物料溯源结束
                    sixWuliaoinfoMapper.deleteSixWuliaoinfoByhuojiacode(huojiahao);
                    //将出库货架所有关联货位状态为free
                    bindcangweiornobind(huojiahao, 0, 0);
//        String strName = sysDibiao1.getName();
                    // TODO  strName为出库位货架地标号，endName 终点位置
                    map.put("code", 200);
                    map.put("msg", "执行成功！");

                    //同步修改空闲等待任务中的出库位货架清空完成状态
//                    SixFreetask sixFreetask1 = new SixFreetask();
//                    sixFreetask1.setType("5");
//                    sixFreetask1.setHuojia(huojiahao);
//                    sixFreetask1.setTasking("1");
//                    sixFreetaskMapper.updateSixFreetaskByTypeAndHuojia(sixFreetask1);
                }else{
                    map.put("code", 100);
                    map.put("msg", "请正确输入仓位编号！");
                }
//            }else{
//                map.put("code", 100);
//                map.put("msg", "请在出库位清空货架！");
//            }
//        }else{
//            map.put("code", 100);
//            map.put("msg", "请正确输入仓位编号！");
//        }
//        }
        return map;
    }



    public void bindcangweiornobind(String position, long isrequest, long isfree) {
        SysStorage sysStorage = new SysStorage();
        sysStorage.setLieType(position);
        List<Map<String, Object>> list = sysStorageMapper.selectSysStorageList(sysStorage);
        for (Map<String, Object> map : list) {
            sysStorage.setCangweiNo(null);
            sysStorage.setId(Long.parseLong(map.get("id").toString()));
            sysStorage.setIsRequest(isrequest);
            sysStorage.setIsFree(isfree);
            sysStorageMapper.updateSysStorage(sysStorage);
        }
    }
    private static String rcsUrl = "http://172.16.0.200:8182/rcms/services/rest/hikRpcService/";
    public static String gainStr(String cangweino){
        String response = "";
        String param = "{\n" +
                "    \"reqCode\": \"\",\n" +
                "    \"reqTime\": \"\",\n" +
                "    \"clientCode\": \"\",\n" +
                "    \"tokenCode\": \"\",\n" +
                "    \"ctnrTyp\": \"1\",\n" +
                "    \"ctnrCode\": \"\",\n" +
                "    \"wbCode\": \"\",\n" +
                "    \"podCode\": \"\",\n" +
                "    \"podDir\": \"\",\n" +
                "    \"podTyp\": \"\",\n" +
                "    \"materialLot\": \"\",\n" +
                "    \"agvCode\": \"\",\n" +
                "    \"taskCode\": \"\",\n" +
                "    \"stgBinCode\": \""+cangweino+"\",\n" +
                "    \"indBind\": \"0\",\n" +
                "    \"data\": \"\"\n" +
                "}";
        JSONObject json = JSONObject.parseObject(param);
        String reqCode = UUID.randomUUID().toString().substring(0, 20);
        json.fluentPut("reqCode", reqCode);
        json.fluentPut("reqTime", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        json.fluentPut("taskCode", reqCode);
        response = HttpUtils.sendRestPost(rcsUrl+"bindCtnrAndBin",json);
        return response;
    }
}
